const CACHE_NAME = "my-cache-v3";
const urlsToCache = ["/index.css"];

caches.delete("my-cache-v2"); // 触发时机
self.addEventListener("activate", (event) => {
  console.log('activate....')
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames
          .filter((name) => name !== CACHE_NAME)
          .map((name) => caches.delete(name))
      );
    })
  );
});
self.addEventListener("install", (event) => {
  console.log("install....");

  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => {
      return cache.addAll(urlsToCache);
    })
  );
});

self.addEventListener("fetch", (event) => {
  console.log("fetch...");
  event.respondWith(
    caches.match(event.request).then(function (resp) {
      return (
        resp ||
        fetch(event.request).then(function (response) {
          return caches.open(CACHE_NAME).then(function (cache) {
            if (!event.request.url.startsWith("chrome-extension://")) {
              cache.put(event.request, response.clone());
            }
            return response;
          });
        })
      );
    })
  );
});
